/**
 * 设备管理状态存储模块
 * 
 * 核心功能：
 * - 设备数据管理
 * - 设备操作状态跟踪
 * - 模拟流程状态管理
 * 
 * 最小实现调用方式：
 * import { useDeviceStore } from '@/stores/device'
 * const deviceStore = useDeviceStore()
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import * as deviceApi from '@/api/device'

export const useDeviceStore = defineStore('device', () => {
  // 状态定义
  const devices = ref([])
  const currentDevice = ref(null)
  const loading = ref(false)
  const simulationState = ref({
    currentImage: null,
    imageHistory: [],
    clickableAreas: []
  })
  const widgetLibrary = ref([]) // 控件库

  // 计算属性
  const deviceCount = computed(() => devices.value.length)
  const hasDevices = computed(() => devices.value.length > 0)

  // 获取设备列表
  const fetchDevices = async () => {
    console.log('获取设备列表...')
    loading.value = true
    try {
      const response = await deviceApi.getDevices()
      devices.value = response.data
      console.log(`成功获取${devices.value.length}个设备`)
    } catch (error) {
      console.error('获取设备列表失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 添加设备 - 正确的逻辑：设备类型直接作为一级列表，设备名称作为二级记录
  const addDevice = async (deviceData) => {
    console.log('=== 添加设备开始 ===')
    console.log('设备名称:', deviceData.name)
    console.log('设备类型:', deviceData.deviceType)
    console.log('所属分类:', deviceData.category)
    
    loading.value = true
    try {
      const response = await deviceApi.createDevice(deviceData)
      const newDevice = response.data
      
      const deviceType = deviceData.deviceType // 这将成为一级列表名（如"超声设备"）
      const deviceName = deviceData.name // 这将成为二级记录名（如"B超"）
      const category = deviceData.category // 顶级分类（如"medical_imaging"）
      
      console.log('=== 目标结构 ===')
      console.log('一级列表(设备类型):', deviceType)
      console.log('二级记录(设备名称):', deviceName)
      console.log('所属顶级分类:', category)
      
      // 查找或创建设备类型（一级列表）
      let deviceTypeCategory = devices.value.find(d => 
        d.name === deviceType && 
        d.type === 'category' && 
        d.category === category &&
        d.isCategory === true
      )
      
      if (!deviceTypeCategory) {
        // 创建新的设备类型（一级列表）
        console.log('创建新的一级列表:', deviceType)
        deviceTypeCategory = {
          id: `${category}_${deviceType.toLowerCase().replace(/[\s\u4e00-\u9fff]+/g, '_')}_${Date.now()}`,
          name: deviceType, // 这是一级列表名（如"超声设备"）
          description: `${deviceType}设备类型`,
          type: 'category', // 标记为分类类型，但它是一级列表
          category: category, // 记录所属的顶级分类
          status: 'active',
          isCategory: true, // 标记为分类类型
          imageCount: 0,
          thumbnail: null,
          images: [],
          coordinateLog: null,
          coordinateFiles: [],
          children: [] // 这里存放具体设备（二级记录）
        }
        
        devices.value.push(deviceTypeCategory)
        console.log('一级列表创建成功:', deviceType)
      } else {
        console.log('找到已存在的一级列表:', deviceTypeCategory.name)
      }
      
      // 将具体设备添加到设备类型下作为二级记录
      if (!deviceTypeCategory.children) {
        deviceTypeCategory.children = []
      }
      
      // 检查是否已存在相同设备
      const existingDeviceIndex = deviceTypeCategory.children.findIndex(d => 
        d.name === newDevice.name || d.id === newDevice.id
      )
      
      if (existingDeviceIndex === -1) {
        // 设置新设备的父级关系
        newDevice.parentId = deviceTypeCategory.id
        newDevice.type = 'device' // 标记为具体设备
        newDevice.category = category
        
        // 添加设备到设备类型下（作为二级记录）
        deviceTypeCategory.children.push(newDevice)
        
        // 更新设备类型的统计信息和文件
        deviceTypeCategory.imageCount = (deviceTypeCategory.imageCount || 0) + (newDevice.images?.length || 0)
        
        // 更新设备类型缩略图
        if (newDevice.images && newDevice.images.length > 0) {
          if (!deviceTypeCategory.thumbnail) {
            deviceTypeCategory.thumbnail = newDevice.images[0].thumbnail || newDevice.images[0].url
          }
          // 合并图片到设备类型
          if (!deviceTypeCategory.images) {
            deviceTypeCategory.images = []
          }
          deviceTypeCategory.images.push(...newDevice.images)
        }
        
        // 合并坐标文件到设备类型
        if (newDevice.coordinateFiles && newDevice.coordinateFiles.length > 0) {
          if (!deviceTypeCategory.coordinateFiles) {
            deviceTypeCategory.coordinateFiles = []
          }
          deviceTypeCategory.coordinateFiles.push(...newDevice.coordinateFiles)
        }
        
        // 合并坐标日志到设备类型
        if (newDevice.coordinateLog && !deviceTypeCategory.coordinateLog) {
          deviceTypeCategory.coordinateLog = newDevice.coordinateLog
        }
        
        console.log('=== 设备添加成功 ===')
        console.log('一级列表(设备类型):', deviceType, '(ID:', deviceTypeCategory.id, ')')
        console.log('二级记录(设备名称):', deviceName, '(ID:', newDevice.id, ')')
        console.log('层级关系:', deviceType, '->', deviceName)
        console.log('图片数量:', newDevice.images?.length || 0)
        console.log('坐标文件数量:', newDevice.coordinateFiles?.length || 0)
      } else {
        // 更新现有设备
        deviceTypeCategory.children[existingDeviceIndex] = {
          ...deviceTypeCategory.children[existingDeviceIndex],
          ...newDevice
        }
        console.log('设备已存在，更新现有设备:', newDevice.name)
      }
      
      // 触发响应式更新
      devices.value = [...devices.value]
      
      console.log('=== 最终结构验证 ===')
      console.log('列表中将显示:', deviceType, '(一级列表)')
      console.log('点击后将显示:', deviceName, '(二级记录)')
      console.log('所属分类:', category)
      
      return newDevice
    } catch (error) {
      console.error('添加设备失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }
  
  // 获取分类显示名称
  const getCategoryDisplayName = (category) => {
    const categoryNames = {
      'emergency_life_support': '急救与生命支持',
      'in_vitro_diagnostics': '体外诊断',
      'infusion_pump': '输注泵',
      'medical_imaging': '医学影像',
      'surgical_equipment': '外科设备'
    }
    return categoryNames[category] || category
  }

  // 更新设备 - 支持嵌套结构更新
  const updateDevice = async (deviceId, deviceData) => {
    console.log('=== 更新设备开始 ===')
    console.log('要更新的设备ID:', deviceId)
    console.log('更新数据:', deviceData)
    
    loading.value = true
    try {
      // 先调用API更新
      const response = await deviceApi.updateDevice(deviceId, deviceData)
      const updatedDevice = response.data
      
      // 查找并更新设备（支持嵌套结构）
      let deviceFound = false
      let deviceInfo = null
      
      // 遍历所有设备，查找要更新的设备
      for (let i = 0; i < devices.value.length; i++) {
        const device = devices.value[i]
        
        // 检查是否是顶级设备
        if (device.id === deviceId) {
          deviceInfo = { type: 'top-level', device: device, index: i }
          deviceFound = true
          break
        }
        
        // 检查是否是嵌套设备（在children中）
        if (device.children && Array.isArray(device.children)) {
          for (let j = 0; j < device.children.length; j++) {
            const childDevice = device.children[j]
            if (childDevice.id === deviceId) {
              deviceInfo = { 
                type: 'nested', 
                device: childDevice, 
                parent: device, 
                parentIndex: i, 
                childIndex: j 
              }
              deviceFound = true
              break
            }
          }
        }
        
        if (deviceFound) break
      }
      
      if (!deviceFound) {
        throw new Error('未找到要更新的设备')
      }
      
      console.log('找到设备:', deviceInfo.type, deviceInfo.device.name)
      
      // 根据设备类型执行更新操作
      if (deviceInfo.type === 'top-level') {
        // 更新顶级设备
        devices.value[deviceInfo.index] = updatedDevice
        console.log('更新顶级设备:', updatedDevice.name)
      } else if (deviceInfo.type === 'nested') {
        // 更新嵌套设备
        const parent = deviceInfo.parent
        const oldDevice = deviceInfo.device
        
        console.log('更新嵌套设备:', parent.name, '->', oldDevice.name, '到', updatedDevice.name)
        
        // 更新子设备数据
        parent.children[deviceInfo.childIndex] = updatedDevice
        
        // 重新计算父设备的统计信息
        let totalImageCount = 0
        let allImages = []
        let allCoordinateFiles = []
        let firstThumbnail = null
        
        // 遍历所有子设备，重新计算统计
        parent.children.forEach(child => {
          if (child.images && child.images.length > 0) {
            totalImageCount += child.images.length
            allImages.push(...child.images)
            if (!firstThumbnail) {
              firstThumbnail = child.images[0].thumbnail || child.images[0].url
            }
          }
          
          if (child.coordinateFiles && child.coordinateFiles.length > 0) {
            allCoordinateFiles.push(...child.coordinateFiles)
          }
        })
        
        // 更新父设备统计信息
        parent.imageCount = totalImageCount
        parent.images = allImages
        parent.coordinateFiles = allCoordinateFiles
        parent.thumbnail = firstThumbnail
        
        // 如果有坐标日志，使用第一个子设备的坐标日志
        if (!parent.coordinateLog && parent.children.length > 0) {
          const firstChildWithLog = parent.children.find(child => child.coordinateLog)
          if (firstChildWithLog) {
            parent.coordinateLog = firstChildWithLog.coordinateLog
          }
        }
        
        console.log('嵌套设备更新完成，父设备统计信息已更新')
        console.log('父设备图片数量:', parent.imageCount)
        console.log('父设备子设备数量:', parent.children.length)
      }
      
      // 触发响应式更新
      devices.value = [...devices.value]
      
      console.log('=== 设备更新成功 ===')
      console.log('更新的设备:', updatedDevice.name)
      console.log('更新类型:', deviceInfo.type)
      
      return updatedDevice
    } catch (error) {
      console.error('更新设备失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 删除设备 - 支持嵌套结构删除
  const deleteDevice = async (deviceId) => {
    console.log('=== 删除设备开始 ===')
    console.log('要删除的设备ID:', deviceId)
    
    loading.value = true
    try {
      // 先查找设备位置（在API调用之前）
      let deviceFound = false
      let deviceInfo = null
      
      // 遍历所有设备，查找要删除的设备
      for (let i = 0; i < devices.value.length; i++) {
        const device = devices.value[i]
        
        // 检查是否是顶级设备
        if (device.id === deviceId) {
          deviceInfo = { type: 'top-level', device: device, index: i }
          deviceFound = true
          console.log('Store层找到顶级设备:', device.name, 'ID:', deviceId)
          break
        }
        
        // 检查是否是嵌套设备（在children中）
        if (device.children && Array.isArray(device.children)) {
          for (let j = 0; j < device.children.length; j++) {
            const childDevice = device.children[j]
            if (childDevice.id === deviceId) {
              deviceInfo = { 
                type: 'nested', 
                device: childDevice, 
                parent: device, 
                parentIndex: i, 
                childIndex: j 
              }
              deviceFound = true
              console.log('Store层找到嵌套设备:', childDevice.name, 'ID:', deviceId, '父设备:', device.name)
              break
            }
          }
        }
        
        if (deviceFound) break
      }
      
      console.log('Store层设备查找结果:', deviceFound ? '找到' : '未找到', '设备ID:', deviceId)
      console.log('Store层当前devices数量:', devices.value.length)
      console.log('Store层所有设备ID:', devices.value.map(d => ({ id: d.id, name: d.name, hasChildren: !!d.children, childrenCount: d.children?.length || 0 })))
      
      if (!deviceFound) {
        throw new Error('未找到要删除的设备')
      }
      
      // 调用API删除（在找到设备之后）
      await deviceApi.deleteDevice(deviceId)
      
      console.log('找到设备:', deviceInfo.type, deviceInfo.device.name)
      
      // 根据设备类型执行删除操作
      if (deviceInfo.type === 'top-level') {
        // 删除顶级设备（一级列表）- 只允许删除空分类
        const topLevelDevice = deviceInfo.device
        console.log('删除一级列表:', topLevelDevice.name)
        
        // 检查是否为空分类
        if (topLevelDevice.isCategory && topLevelDevice.children && topLevelDevice.children.length > 0) {
          throw new Error(`无法删除分类"${topLevelDevice.name}"，该分类下还有 ${topLevelDevice.children.length} 个设备`)
        }
        
        // 只删除空的一级列表
        devices.value.splice(deviceInfo.index, 1)
        console.log('空分类删除完成:', topLevelDevice.name)
      } else if (deviceInfo.type === 'nested') {
        // 删除嵌套设备
        const parent = deviceInfo.parent
        const childDevice = deviceInfo.device
        
        console.log('从父设备中删除子设备:', parent.name, '->', childDevice.name)
        
        // 从父设备的children中删除
        parent.children.splice(deviceInfo.childIndex, 1)
        
        // 更新父设备的统计信息
        if (childDevice.images && childDevice.images.length > 0) {
          // 减少图片数量
          parent.imageCount = Math.max(0, (parent.imageCount || 0) - childDevice.images.length)
          
          // 从父设备的images中移除对应图片
          if (parent.images && Array.isArray(parent.images)) {
            parent.images = parent.images.filter(img => 
              !childDevice.images.some(childImg => childImg.id === img.id)
            )
          }
          
          // 如果删除的设备包含缩略图，更新父设备缩略图
          if (parent.thumbnail && childDevice.images.some(img => 
            img.url === parent.thumbnail || img.thumbnail === parent.thumbnail)) {
            // 使用剩余的第一张图片作为缩略图
            if (parent.images && parent.images.length > 0) {
              parent.thumbnail = parent.images[0].thumbnail || parent.images[0].url
            } else {
              parent.thumbnail = null
            }
          }
        }
        
        // 更新坐标文件
        if (childDevice.coordinateFiles && childDevice.coordinateFiles.length > 0) {
          if (parent.coordinateFiles && Array.isArray(parent.coordinateFiles)) {
            parent.coordinateFiles = parent.coordinateFiles.filter(coord => 
              !childDevice.coordinateFiles.some(childCoord => childCoord.name === coord.name)
            )
          }
        }
        
        // 如果父设备没有子设备了，保留空分类但清空相关数据
        if (parent.children.length === 0) {
          console.log('父设备已无子设备，保留空分类但清空数据:', parent.name)
          
          // 清空父设备的统计信息和文件数据，但保留分类结构
          parent.imageCount = 0
          parent.thumbnail = null
          parent.images = []
          parent.coordinateFiles = []
          parent.coordinateLog = null
          
          console.log('空分类已清理数据，用户可手动删除:', parent.name)
          
          // 标记为空分类，但不删除
          deviceInfo.categoryBecameEmpty = true
        }
        
        console.log('嵌套设备删除完成，父设备剩余子设备数量:', parent.children.length)
      }
      
      // 触发响应式更新
      devices.value = [...devices.value]
      
      console.log('=== 设备删除成功 ===')
      console.log('删除的设备:', deviceInfo.device.name)
      console.log('删除类型:', deviceInfo.type)
      console.log('当前设备总数:', devices.value.length)
      
      // 返回删除结果信息
      return {
        success: true,
        deletedDevice: deviceInfo.device,
        deleteType: deviceInfo.type,
        categoryBecameEmpty: deviceInfo.categoryBecameEmpty || false
      }
      
    } catch (error) {
      console.error('删除设备失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 设置当前设备
  const setCurrentDevice = (device) => {
    console.log('设置当前设备:', device?.name)
    currentDevice.value = device
  }

  // 更新模拟状态
  const updateSimulationState = (state) => {
    console.log('更新模拟状态')
    simulationState.value = { ...simulationState.value, ...state }
  }

  // 解析log.txt文件内容
  const parseLogContent = (content) => {
    console.log('开始解析log.txt内容，长度:', content ? content.length : 0)
    
    if (!content || typeof content !== 'string') {
      console.warn('内容为空或不是字符串，返回空对象')
      return {}
    }
    
    let cleanedContent = ''
    
    try {
      // 首先尝试直接解析
      return JSON.parse(content)
    } catch (error) {
      console.log('直接解析失败，尝试清理格式:', error.message)
      
      try {
        // 清理格式后再次解析
        cleanedContent = content
          // 移除单行注释（// 开头的行）
          .replace(/\/\/.*$/gm, '')
          // 移除多行注释（/* */ 包围的内容）
          .replace(/\/\*[\s\S]*?\*\//g, '')
          // 移除中文注释样式（以中文字符开头的行）
          .replace(/^\s*[\u4e00-\u9fff].*$/gm, '')
          // 替换中文逗号
          .replace(/，/g, ',')
          // 智能替换单引号为双引号（不影响字符串内部的单引号）
          .replace(/([:,\[{]\s*)'([^']*)'(\s*[,\]}:])/g, '$1"$2"$3')
          // 给没有引号的键名加双引号
          .replace(/([{,]\s*)([a-zA-Z_][a-zA-Z0-9_]*)\s*:/g, '$1"$2":')
          // 移除多余的逗号（在}或]前的逗号）
          .replace(/,\s*([}\]])/g, '$1')
          // 清理多余的空行和空白字符
          .replace(/^\s*$/gm, '')
          .replace(/\n\s*\n/g, '\n')
          .trim()
        
        console.log('格式清理完成，尝试解析清理后的内容')
        return JSON.parse(cleanedContent)
        
      } catch (error2) {
        console.error('清理后仍无法解析:', error2.message)
        console.error('清理后内容:', cleanedContent)
        
        // 解析失败时，返回空对象而不是抛出错误
        console.warn('解析失败，返回空对象以保护原有数据')
        
        // 尝试手动构建一个基本的JSON结构
        try {
          if (content.includes('main_') || content.includes('UI_')) {
            console.log('检测到可能的UI键，尝试手动构建结构')
            // 这里可以添加更复杂的解析逻辑，但为了安全起见，返回空对象
          }
        } catch (e) {
          console.log('手动构建也失败')
        }
        
        return {} // 安全返回空对象
      }
    }
  }

  // 保存坐标信息到log.txt
  const saveCoordinatesToLog = async (deviceId, pageKey, coordinateInfo) => {
    console.log('=== 开始保存坐标信息到log.txt ===')
    console.log('设备ID:', deviceId, '页面键:', pageKey, '坐标信息:', coordinateInfo)
    
    loading.value = true
    
    try {
      // 查找设备
      let deviceInfo = null
      
      for (let i = 0; i < devices.value.length; i++) {
        const device = devices.value[i]
        
        // 检查顶级设备
        if (device.id === deviceId) {
          deviceInfo = { type: 'top-level', device: device, index: i }
          break
        }
        
        // 检查嵌套设备
        if (device.children && Array.isArray(device.children)) {
          for (let j = 0; j < device.children.length; j++) {
            const childDevice = device.children[j]
            if (childDevice.id === deviceId) {
              deviceInfo = { 
                type: 'nested', 
                device: childDevice, 
                parent: device, 
                parentIndex: i, 
                childIndex: j 
              }
              break
            }
          }
          if (deviceInfo) break
        }
      }
      
      if (!deviceInfo) {
        throw new Error('设备不存在')
      }
      
      const device = deviceInfo.device
      
      if (!device.coordinateLog || !device.coordinateLog.content) {
        throw new Error('设备没有坐标文件')
      }
      
      // 解析现有的log.txt内容
      let coordinateData = {}
      try {
        coordinateData = parseLogContent(device.coordinateLog.content)
        console.log('解析现有log.txt成功，页面数量:', Object.keys(coordinateData).length)
      } catch (parseError) {
        console.error('解析log.txt失败:', parseError)
        throw new Error('解析坐标文件失败')
      }
      
      // 更新指定页面的坐标信息
      const newPageData = [
        { orgin_name: coordinateInfo.orgin_name }
      ]
      
      // 添加所有按钮信息
      if (coordinateInfo.buttons && Array.isArray(coordinateInfo.buttons)) {
        coordinateInfo.buttons.forEach(button => {
          newPageData.push({
            next: button.next || '',
            name: button.name || '',
            x: button.x || 0,
            y: button.y || 0,
            width: button.width || 100,
            height: button.height || 40
          })
        })
      }
      
      coordinateData[pageKey] = newPageData
      
      console.log('更新页面数据:', pageKey, newPageData)
      
      // 将更新后的数据写回log.txt
      device.coordinateLog.content = JSON.stringify(coordinateData, null, 2)
      
      console.log('坐标信息保存成功')
      
      return { success: true }
      
    } catch (error) {
      console.error('保存坐标信息失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 删除设备图片
  const deleteDeviceImage = async (deviceId, imageIndex) => {
    console.log('=== 开始删除设备图片 ===')
    console.log('设备ID:', deviceId, '图片索引:', imageIndex)
    
    loading.value = true
    
    try {
      // 查找设备位置
      let deviceInfo = null
      
      for (let i = 0; i < devices.value.length; i++) {
        const device = devices.value[i]
        
        // 检查顶级设备
        if (device.id === deviceId) {
          deviceInfo = { type: 'top-level', device: device, index: i }
          break
        }
        
        // 检查嵌套设备
        if (device.children && Array.isArray(device.children)) {
          for (let j = 0; j < device.children.length; j++) {
            const childDevice = device.children[j]
            if (childDevice.id === deviceId) {
              deviceInfo = { 
                type: 'nested', 
                device: childDevice, 
                parent: device, 
                parentIndex: i, 
                childIndex: j 
              }
              break
            }
          }
          if (deviceInfo) break
        }
      }
      
      if (!deviceInfo) {
        throw new Error('设备不存在')
      }
      
      const device = deviceInfo.device
      
      if (!device.images || !Array.isArray(device.images) || imageIndex < 0 || imageIndex >= device.images.length) {
        throw new Error('图片索引无效')
      }
      
      const imageToDelete = device.images[imageIndex]
      console.log('要删除的图片:', imageToDelete.name)
      
      // 调用API删除图片
      await deviceApi.deleteDeviceImage(deviceId, imageIndex)
      
      // 处理log.txt文件中的坐标信息
      if (device.coordinateLog && device.coordinateLog.content) {
        try {
          console.log('开始处理log.txt文件，删除对应的UI键')
          
          // 保存原始内容备份（只在第一次时保存）
          if (!device.coordinateLog.originalContent) {
            device.coordinateLog.originalContent = device.coordinateLog.content || '{}'
          }
          
          // 优先使用原始内容进行解析
          let sourceContent = device.coordinateLog.originalContent || device.coordinateLog.content || '{}'
          let coordinateData = {}
          
          try {
            coordinateData = parseLogContent(sourceContent)
            console.log('解析log.txt成功，当前UI键数量:', Object.keys(coordinateData).length)
          } catch (parseError) {
            console.warn('解析log.txt失败，跳过坐标更新:', parseError.message)
            // 解析失败时跳过坐标更新，只删除图片
          }
          
          // 如果解析成功，查找并删除对应的UI键
          if (Object.keys(coordinateData).length > 0) {
            let deletedKey = null
            
            // 准备多种可能的匹配名称
            const imageNameWithoutExt = imageToDelete.name.replace(/\.[^/.]+$/, "")
            console.log('尝试删除图片对应的UI键，图片名:', imageToDelete.name, '去扩展名:', imageNameWithoutExt)
            
            const possibleKeys = [
              imageToDelete.name,           // 完整文件名 (如 "main_1.jpg")
              imageNameWithoutExt,          // 去掉扩展名 (如 "main_1")
              imageToDelete.name.toLowerCase(),
              imageNameWithoutExt.toLowerCase()
            ]
            
            // 方法1：直接通过键名匹配（最常见的情况）
            for (const possibleKey of possibleKeys) {
              if (coordinateData[possibleKey]) {
                delete coordinateData[possibleKey]
                deletedKey = possibleKey
                console.log('✅ 通过键名直接匹配删除UI键:', possibleKey)
                break
              }
            }
            
            // 方法2：如果直接匹配失败，尝试通过orgin_name字段匹配
            if (!deletedKey) {
              for (const key in coordinateData) {
                if (coordinateData[key] && Array.isArray(coordinateData[key]) && coordinateData[key].length > 0) {
                  const firstItem = coordinateData[key][0]
                  if (firstItem && firstItem.orgin_name) {
                    // 检查orgin_name是否与图片名匹配
                    if (possibleKeys.includes(firstItem.orgin_name) || 
                        possibleKeys.some(pk => pk.includes(firstItem.orgin_name)) ||
                        possibleKeys.some(pk => firstItem.orgin_name.includes(pk))) {
                      delete coordinateData[key]
                      deletedKey = key
                      console.log('✅ 通过orgin_name字段匹配删除UI键:', key, 'orgin_name:', firstItem.orgin_name)
                      break
                    }
                  }
                }
              }
            }
            
            if (deletedKey) {
              // 更新log.txt内容
              device.coordinateLog.content = JSON.stringify(coordinateData, null, 2)
              console.log('log.txt更新成功，删除了UI键:', deletedKey)
      } else {
              console.log('未找到图片对应的UI键:', imageToDelete.name)
            }
          }
          
        } catch (error) {
          console.error('处理log.txt文件时发生错误:', error)
          // 即使log.txt处理失败，也继续删除图片
        }
      }
      
      // 从设备图片数组中删除
      device.images.splice(imageIndex, 1)
      
      // 更新设备的图片统计信息
      device.imageCount = device.images.length
      
      // 如果删除的是缩略图，重新设置缩略图
      if (device.thumbnail === imageToDelete.url || device.thumbnail === imageToDelete.thumbnail) {
        device.thumbnail = device.images.length > 0 ? (device.images[0].thumbnail || device.images[0].url) : null
      }
      
      // 如果是嵌套设备，更新父设备的统计信息
      if (deviceInfo.type === 'nested') {
        const parent = deviceInfo.parent
        let totalImages = 0
        let firstThumbnail = null
        
          parent.children.forEach(child => {
          if (child.images && child.images.length > 0) {
              totalImages += child.images.length
            if (!firstThumbnail) {
                firstThumbnail = child.images[0].thumbnail || child.images[0].url
              }
            }
          })
        
        parent.imageCount = totalImages
        parent.thumbnail = firstThumbnail
      }
      
      // 触发响应式更新
      devices.value = [...devices.value]
      
      console.log('图片删除成功:', imageToDelete.name)
      console.log('设备剩余图片数量:', device.images.length)
      
      return {
        success: true,
        deletedImage: imageToDelete,
        remainingCount: device.images.length
      }
      
    } catch (error) {
      console.error('删除设备图片失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }
  
  // 添加设备图片
  const addDeviceImage = async (deviceId, imageFile) => {
    console.log('=== 开始添加设备图片 ===')
    console.log('设备ID:', deviceId, '图片文件:', imageFile.name)
    
    loading.value = true
    
    try {
      // 查找设备位置
      let deviceInfo = null
      
      for (let i = 0; i < devices.value.length; i++) {
        const device = devices.value[i]
        
        // 检查顶级设备
        if (device.id === deviceId) {
          deviceInfo = { type: 'top-level', device: device, index: i }
          break
        }
        
        // 检查嵌套设备
        if (device.children && Array.isArray(device.children)) {
          for (let j = 0; j < device.children.length; j++) {
            const childDevice = device.children[j]
            if (childDevice.id === deviceId) {
              deviceInfo = { 
                type: 'nested', 
                device: childDevice, 
                parent: device, 
                parentIndex: i, 
                childIndex: j 
              }
              break
            }
          }
          if (deviceInfo) break
        }
      }
      
      if (!deviceInfo) {
        throw new Error('设备不存在')
      }
      
      const device = deviceInfo.device
      
      // 调用API添加图片
      const response = await deviceApi.addDeviceImage(deviceId, imageFile)
      const newImage = response.data
      
      console.log('API返回的新图片信息:', newImage)
      
      // 初始化图片数组（如果不存在）
      if (!device.images) {
        device.images = []
      }
      
      // 处理log.txt文件中的坐标信息
      if (device.coordinateLog && device.coordinateLog.content) {
        try {
          console.log('开始处理log.txt文件，添加新的UI键')
          
          // 保存原始内容备份（只在第一次时保存）
          if (!device.coordinateLog.originalContent) {
            device.coordinateLog.originalContent = device.coordinateLog.content || '{}'
          }
          
          // 优先使用原始内容进行解析
          let sourceContent = device.coordinateLog.originalContent || device.coordinateLog.content || '{}'
          let coordinateData = {}
          
          try {
            coordinateData = parseLogContent(sourceContent)
            console.log('解析log.txt成功，当前UI键数量:', Object.keys(coordinateData).length)
          } catch (parseError) {
            console.warn('解析log.txt失败，跳过坐标更新:', parseError.message)
            // 解析失败时跳过坐标更新，只添加图片
          }
          
          // 如果解析成功，为新图片生成UI键
          if (Object.keys(coordinateData).length >= 0) {
            // 生成新的UI键名
            const existingKeys = Object.keys(coordinateData)
            let newKeyIndex = 1
            let newKey = `UI_${newKeyIndex}_0_0_0`
            
            // 找到一个不重复的UI键名
            while (existingKeys.includes(newKey)) {
              newKeyIndex++
              newKey = `UI_${newKeyIndex}_0_0_0`
            }
            
            // 为新图片创建基础的坐标记录
            coordinateData[newKey] = [
              {
                orgin_name: newImage.name
              }
            ]
            
            console.log('为新图片生成UI键:', newKey, '图片名称:', newImage.name)
            
            // 更新log.txt内容
            device.coordinateLog.content = JSON.stringify(coordinateData, null, 2)
            console.log('log.txt更新成功，添加了UI键:', newKey)
          }
          
        } catch (error) {
          console.error('处理log.txt文件时发生错误:', error)
          // 即使log.txt处理失败，也继续添加图片
        }
      }
      
      // 添加新图片到设备
      device.images.push(newImage)
      
      // 更新设备的图片统计信息
      device.imageCount = device.images.length
      
      // 如果是第一张图片，设置为缩略图
      if (device.images.length === 1) {
        device.thumbnail = newImage.thumbnail || newImage.url
      }
      
      // 如果是嵌套设备，更新父设备的统计信息
      if (deviceInfo.type === 'nested') {
        const parent = deviceInfo.parent
        let totalImages = 0
        let firstThumbnail = null
        
          parent.children.forEach(child => {
          if (child.images && child.images.length > 0) {
              totalImages += child.images.length
            if (!firstThumbnail) {
                firstThumbnail = child.images[0].thumbnail || child.images[0].url
              }
            }
          })
        
        parent.imageCount = totalImages
        if (!parent.thumbnail) {
        parent.thumbnail = firstThumbnail
        }
      }
      
      // 触发响应式更新
      devices.value = [...devices.value]
      
      console.log('图片添加成功:', newImage.name)
      console.log('设备当前图片数量:', device.images.length)
      
      return {
        success: true,
        addedImage: newImage,
        totalCount: device.images.length
      }
      
    } catch (error) {
      console.error('添加设备图片失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 更新设备信息（名称和类型）并迁移设备类型
  const updateDeviceInfo = async (deviceId, newName, newDeviceType, category) => {
    console.log('=== 更新设备信息开始 ===')
    console.log('设备ID:', deviceId)
    console.log('新设备名称:', newName)
    console.log('新设备类型:', newDeviceType)
    console.log('所属分类:', category)
    
    loading.value = true
    
    try {
      // 1. 查找设备位置
      let deviceInfo = null
      
      for (let i = 0; i < devices.value.length; i++) {
        const device = devices.value[i]
        
        // 检查是否是嵌套设备（在children中）
        if (device.children && Array.isArray(device.children)) {
          for (let j = 0; j < device.children.length; j++) {
            const childDevice = device.children[j]
            if (childDevice.id === deviceId) {
              deviceInfo = { 
                type: 'nested', 
                device: childDevice, 
                parent: device, 
                parentIndex: i, 
                childIndex: j 
              }
              break
            }
          }
        }
        
        if (deviceInfo) break
      }
      
      if (!deviceInfo || deviceInfo.type !== 'nested') {
        throw new Error('只能更新具体设备的信息')
      }
      
      const oldParent = deviceInfo.parent
      const targetDevice = deviceInfo.device
      const oldDeviceType = oldParent.name
      
      console.log('找到设备:', targetDevice.name)
      console.log('当前设备类型(父级):', oldDeviceType)
      console.log('新设备类型:', newDeviceType)
      
      // 2. 更新设备名称
      targetDevice.name = newName
      
      // 3. 判断是否需要迁移设备类型
      if (oldDeviceType !== newDeviceType) {
        console.log('设备类型发生变化，需要迁移设备')
        
        // 3.1 从旧的设备类型中移除
        oldParent.children.splice(deviceInfo.childIndex, 1)
        console.log(`从旧设备类型"${oldDeviceType}"中移除设备`)
        
        // 3.2 更新旧父设备的统计信息
        let oldParentTotalImages = 0
        let oldParentImages = []
        let oldParentCoordinateFiles = []
        let oldParentFirstThumbnail = null
        
        oldParent.children.forEach(child => {
          if (child.images && child.images.length > 0) {
            oldParentTotalImages += child.images.length
            oldParentImages.push(...child.images)
            if (!oldParentFirstThumbnail) {
              oldParentFirstThumbnail = child.images[0].thumbnail || child.images[0].url
            }
          }
          if (child.coordinateFiles && child.coordinateFiles.length > 0) {
            oldParentCoordinateFiles.push(...child.coordinateFiles)
          }
        })
        
        oldParent.imageCount = oldParentTotalImages
        oldParent.images = oldParentImages
        oldParent.coordinateFiles = oldParentCoordinateFiles
        oldParent.thumbnail = oldParentFirstThumbnail
        oldParent.coordinateLog = oldParent.children.length > 0 ? oldParent.children[0].coordinateLog : null
        
        console.log('旧设备类型更新完成，剩余子设备数量:', oldParent.children.length)
        
        // 3.3 查找或创建新的设备类型
        let newParent = devices.value.find(d => 
          d.name === newDeviceType && 
          d.type === 'category' && 
          d.category === category &&
          d.isCategory === true
        )
        
        if (!newParent) {
          // 创建新的设备类型
          console.log('创建新的设备类型:', newDeviceType)
          newParent = {
            id: `${category}_${newDeviceType.toLowerCase().replace(/[\s\u4e00-\u9fff]+/g, '_')}_${Date.now()}`,
            name: newDeviceType,
            description: `${newDeviceType}设备类型`,
            type: 'category',
            category: category,
            status: 'active',
            isCategory: true,
            imageCount: 0,
            thumbnail: null,
            images: [],
            coordinateLog: null,
            coordinateFiles: [],
            children: []
          }
          devices.value.push(newParent)
          console.log('新设备类型创建成功')
        } else {
          console.log('找到已存在的设备类型:', newDeviceType)
        }
        
        // 3.4 将设备添加到新的设备类型下
        targetDevice.parentId = newParent.id
        newParent.children.push(targetDevice)
        console.log(`设备已迁移到新设备类型"${newDeviceType}"`)
        
        // 3.5 更新新父设备的统计信息
        let newParentTotalImages = 0
        let newParentImages = []
        let newParentCoordinateFiles = []
        let newParentFirstThumbnail = null
        
        newParent.children.forEach(child => {
          if (child.images && child.images.length > 0) {
            newParentTotalImages += child.images.length
            newParentImages.push(...child.images)
            if (!newParentFirstThumbnail) {
              newParentFirstThumbnail = child.images[0].thumbnail || child.images[0].url
            }
          }
          if (child.coordinateFiles && child.coordinateFiles.length > 0) {
            newParentCoordinateFiles.push(...child.coordinateFiles)
          }
        })
        
        newParent.imageCount = newParentTotalImages
        newParent.images = newParentImages
        newParent.coordinateFiles = newParentCoordinateFiles
        newParent.thumbnail = newParentFirstThumbnail
        if (!newParent.coordinateLog && targetDevice.coordinateLog) {
          newParent.coordinateLog = targetDevice.coordinateLog
        }
        
        console.log('新设备类型更新完成，子设备数量:', newParent.children.length)
        
        // 3.6 如果旧设备类型为空，删除它
        if (oldParent.children.length === 0) {
          console.log('旧设备类型已无子设备，删除空分类:', oldParent.name)
          const oldParentIndex = devices.value.findIndex(d => d.id === oldParent.id)
          if (oldParentIndex !== -1) {
            devices.value.splice(oldParentIndex, 1)
            console.log('空的旧设备类型已删除')
          }
        }
      } else {
        console.log('设备类型未变化，只更新名称')
        
        // 只更新名称，不需要迁移
        // 更新父设备的统计信息（因为子设备名称变了）
        let parentTotalImages = 0
        let parentImages = []
        let parentCoordinateFiles = []
        let parentFirstThumbnail = null
        
        oldParent.children.forEach(child => {
          if (child.images && child.images.length > 0) {
            parentTotalImages += child.images.length
            parentImages.push(...child.images)
            if (!parentFirstThumbnail) {
              parentFirstThumbnail = child.images[0].thumbnail || child.images[0].url
            }
          }
          if (child.coordinateFiles && child.coordinateFiles.length > 0) {
            parentCoordinateFiles.push(...child.coordinateFiles)
          }
        })
        
        oldParent.imageCount = parentTotalImages
        oldParent.images = parentImages
        oldParent.coordinateFiles = parentCoordinateFiles
        oldParent.thumbnail = parentFirstThumbnail
      }
      
      // 触发响应式更新
      devices.value = [...devices.value]
      
      console.log('=== 设备信息更新成功 ===')
      console.log('更新的设备:', newName)
      console.log('设备类型:', newDeviceType)
      
      return {
        success: true,
        deviceName: newName,
        deviceType: newDeviceType,
        migrated: oldDeviceType !== newDeviceType
      }
      
    } catch (error) {
      console.error('更新设备信息失败:', error)
      throw error
    } finally {
      loading.value = false
    }
  }

  // 构建控件库
  const buildWidgetLibrary = (device) => {
    console.log('=== 开始构建控件库 ===')
    console.log('设备:', device.name)
    
    if (!device.coordinateLog || !device.coordinateLog.content) {
      console.log('没有坐标文件，无法构建控件库')
      widgetLibrary.value = []
      return []
    }
    
    try {
      const coordinateData = parseLogContent(device.coordinateLog.content)
      const allButtons = []
      
      // 收集所有按钮信息
      for (const [pageKey, pageData] of Object.entries(coordinateData)) {
        if (Array.isArray(pageData) && pageData.length > 1) {
          const buttons = pageData.slice(1).filter(btn => 
            btn && 
            typeof btn === 'object' && 
            btn.x !== undefined && 
            btn.y !== undefined &&
            btn.width !== undefined &&
            btn.height !== undefined
          )
          
          buttons.forEach(btn => {
            allButtons.push({
              pageKey: pageKey,
              name: btn.name || '',
              next: btn.next || '',
              x: btn.x || 0,
              y: btn.y || 0,
              width: btn.width || 100,
              height: btn.height || 40
            })
          })
        }
      }
      
      console.log('收集到的按钮总数:', allButtons.length)
      
      // 查找重复的控件（名称、尺寸、跳转相同）
      const widgetMap = new Map()
      
      allButtons.forEach(btn => {
        // 生成控件的唯一标识（不包括坐标位置）
        const widgetKey = `${btn.name}_${btn.width}x${btn.height}_${btn.next}`
        
        if (!widgetMap.has(widgetKey)) {
          widgetMap.set(widgetKey, {
            name: btn.name,
            next: btn.next,
            x: btn.x,           // 保存第一次出现的x坐标
            y: btn.y,           // 保存第一次出现的y坐标
            width: btn.width,
            height: btn.height,
            count: 1,
            pages: [btn.pageKey],
            coordinates: [{ x: btn.x, y: btn.y, page: btn.pageKey }] // 保存所有出现的坐标
          })
        } else {
          const widget = widgetMap.get(widgetKey)
          widget.count++
          if (!widget.pages.includes(btn.pageKey)) {
            widget.pages.push(btn.pageKey)
          }
          // 记录这个控件的所有坐标位置
          widget.coordinates.push({ x: btn.x, y: btn.y, page: btn.pageKey })
        }
      })
      
      // 只保留出现2次以上的控件
      const widgets = Array.from(widgetMap.values())
        .filter(w => w.count >= 2)
        .sort((a, b) => b.count - a.count) // 按出现次数降序排列
      
      widgetLibrary.value = widgets
      
      console.log('控件库构建完成，控件数量:', widgets.length)
      console.log('控件列表:', widgets.map(w => ({
        name: w.name,
        count: w.count,
        pages: w.pages.length
      })))
      
      return widgets
      
    } catch (error) {
      console.error('构建控件库失败:', error)
      widgetLibrary.value = []
      return []
    }
  }

  return {
    // 状态
    devices,
    currentDevice,
    loading,
    simulationState,
    widgetLibrary,
    // 计算属性
    deviceCount,
    hasDevices,
    // 方法
    fetchDevices,
    addDevice,
    updateDevice,
    deleteDevice,
    deleteDeviceImage,
    addDeviceImage,
    setCurrentDevice,
    updateSimulationState,
    parseLogContent,
    saveCoordinatesToLog,
    updateDeviceInfo,
    buildWidgetLibrary,
    classifyDeviceImages
  }

  // 设备图片智能分类功能
  function classifyDeviceImages(device) {
    console.log('=== 开始设备图片分类 ===')
    console.log('设备信息:', device.name)
    console.log('图片数量:', device.images?.length || 0)
    
    if (!device.coordinateLog || !device.coordinateLog.content) {
      console.log('没有坐标文件，将所有图片放入"其他"分类')
      return {
        folders: device.images?.length > 0 ? [{
          name: '其他',
          images: device.images,
          keys: []
        }] : [],
        coordinateLog: device.coordinateLog
      }
    }
    
    try {
      // 解析log.txt内容
      const coordinateData = parseLogContent(device.coordinateLog.content)
      const uiKeys = Object.keys(coordinateData)
      
      console.log('解析到的UI键:', uiKeys)
      
      // 分析UI键，提取分类规则
      const folderMap = new Map()
      const otherKeys = []
      
      uiKeys.forEach(key => {
        // 检查是否符合UI_X_Y_Z_W格式
        const uiMatch = key.match(/^UI_(\d+)_\d+_\d+_\d+$/)
        
        if (uiMatch) {
          const firstNumber = uiMatch[1] // 提取第一个数字
          
          if (!folderMap.has(firstNumber)) {
            // 获取该键对应的orgin_name作为文件夹名
            const keyData = coordinateData[key]
            let folderName = '未命名文件夹'
            
            if (Array.isArray(keyData) && keyData.length > 0 && keyData[0].orgin_name) {
              folderName = keyData[0].orgin_name
            }
            
            folderMap.set(firstNumber, {
              name: folderName,
              keys: [key],
              firstKey: key
            })
          } else {
            folderMap.get(firstNumber).keys.push(key)
          }
        } else {
          otherKeys.push(key)
        }
      })
      
      console.log('分类结果:', {
        folders: Array.from(folderMap.entries()),
        otherKeys: otherKeys
      })
      
      // 创建分类结果
      const folders = []
      
      // 按数字顺序排序文件夹
      const sortedFolders = Array.from(folderMap.entries()).sort((a, b) => {
        return parseInt(a[0]) - parseInt(b[0])
      })
      
      // 为每个文件夹分配对应的图片
      sortedFolders.forEach(([number, folderInfo]) => {
        const folderImages = []
        
        // 遍历该文件夹的所有键，查找对应的图片
        folderInfo.keys.forEach(key => {
          // 尝试多种匹配方式查找图片
          const possibleImageNames = [
            key + '.png',
            key + '.jpg',
            key + '.jpeg',
            key.toLowerCase() + '.png',
            key.toLowerCase() + '.jpg',
            key.toLowerCase() + '.jpeg'
          ]
          
          device.images?.forEach(image => {
            const imageName = image.name || ''
            const imageNameWithoutExt = imageName.replace(/\.[^/.]+$/, "")
            
            // 检查是否匹配
            if (possibleImageNames.includes(imageName.toLowerCase()) || 
                imageNameWithoutExt.toLowerCase() === key.toLowerCase()) {
              // 避免重复添加
              if (!folderImages.find(img => img.id === image.id)) {
                folderImages.push(image)
              }
            }
          })
        })
        
        // ✅ 新增逻辑：即使log.txt中没有定义，也检查图片文件名是否符合UI_X_格式
        // 这样可以将符合命名规则但未在log.txt中定义的图片也归类到正确的文件夹
        device.images?.forEach(image => {
          const imageName = image.name || ''
          const imageNameWithoutExt = imageName.replace(/\.[^/.]+$/, "")
          
          // 检查图片文件名是否符合UI_X_Y_Z_W格式
          const imageUiMatch = imageNameWithoutExt.match(/^UI_(\d+)_\d+_\d+_\d+$/)
          
          if (imageUiMatch && imageUiMatch[1] === number) {
            // 图片文件名的第一个数字与当前文件夹匹配
            // 避免重复添加（可能已经通过log.txt键匹配过了）
            if (!folderImages.find(img => img.id === image.id)) {
              console.log(`根据文件名格式归类图片: ${imageName} -> 文件夹${number}(${folderInfo.name})`)
              folderImages.push(image)
            }
          }
        })
        
        if (folderImages.length > 0) {
          folders.push({
            name: folderInfo.name,
            images: folderImages,
            keys: folderInfo.keys
          })
        }
      })
      
      // 处理"其他"分类 - 没有匹配到任何UI键的图片
      const allClassifiedImages = folders.reduce((acc, folder) => {
        return acc.concat(folder.images)
      }, [])
      
      const otherImages = device.images?.filter(image => {
        return !allClassifiedImages.find(classified => classified.id === image.id)
      }) || []
      
      if (otherImages.length > 0) {
        folders.push({
          name: '引导界面',
          images: otherImages,
          keys: otherKeys
        })
      }
      
      console.log('最终分类结果:', folders.map(f => ({
        name: f.name,
        imageCount: f.images.length,
        keys: f.keys
      })))
      
      return {
        folders: folders,
        coordinateLog: device.coordinateLog
      }
      
    } catch (error) {
      console.error('图片分类失败:', error)
      // 分类失败时，将所有图片放入"其他"分类
  return {
        folders: device.images?.length > 0 ? [{
          name: '其他',
          images: device.images,
          keys: []
        }] : [],
        coordinateLog: device.coordinateLog
      }
    }
  }
})

